/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import ejb.CustomerEntity;
import ejb.CustomerEntityFacade;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author mohan
 */
@WebServlet(name = "AddCustomer", urlPatterns = {"/AddCustomer"})
public class AddCustomer extends HttpServlet {
    
    @EJB
    private CustomerEntityFacade customerEntityFacade;

    
    
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        
        String cus_ID = "";
        String cus_Name = "";
        String cus_Address = "";
        String cus_tno = "";
        
        //This Variable used to give the output message to user
        String out_msg ="";
        
        String customer_ID = request.getParameter("customerID"); 
        String name = request.getParameter("name");  
        String address = request.getParameter("address");
        String contactNo = request.getParameter("contactNo");
        
        String cusID = request.getParameter("cusID");
        String act = request.getParameter("act");
        AppOptions apo = new AppOptions();
        
        
        //Used to add a new customer to the database
        if (act != null && act.equals("Add Customer")) 
        {
            if((! customer_ID.isEmpty()) && (! name.isEmpty()) && (! address.isEmpty()) && (! address.isEmpty()))
            {
                Long customerID = Long.parseLong(customer_ID);
                
                if(! apo.checkCustomer(customerID))
                {
                    try{
                        
                        CustomerEntity e = new CustomerEntity();
                        e.setCustomerid(customerID);
                        e.setName(name);
                        e.setAddress(address);
                        e.setContactno(contactNo);
                        customerEntityFacade.create(e);
                        out_msg = "Customer Details Inserted Successfully";
                    }
            
                    
                    catch(Exception ex)
                    {
                        out_msg = "The Format of the Customer ID is wrong";
                    }
                }
                
                else
                {
                    out_msg = "Already There is Customer with the same Customer ID";
                }
            }
            
            else
            {
                out_msg = "Fill the necessary Fields correctly";
            }
        }
        
        //Used to update an existing customer in the database
        else if(act != null && act.equals("Update Customer"))
        {
            String cusKey = request.getParameter("cusKey");
            Long cusKeyID = Long.parseLong(cusKey);            
            if((! customer_ID.isEmpty()) && (! name.isEmpty()) && (! address.isEmpty()) && (! address.isEmpty()))
            {
                Long customerID = Long.parseLong(customer_ID);
                
                try{
                   
                    
                    CustomerEntity e = customerEntityFacade.find(cusKeyID); 
                    e.setCustomerid(customerID);
                    e.setName(name);
                    e.setAddress(address);
                    e.setContactno(contactNo);
                    customerEntityFacade.edit(e);
                    out_msg = "Customer Details Updated Successfully";
                 }
            
                 
                    
                 catch(Exception ex)
                 {
                        out_msg = "The Format of the Customer ID is wrong";
                 }
               
            }
            
            else
            {
                out_msg = "Fill the necessary Fields correctly";
            }
            
        }
        
        //Used to get the customer details of a specific customer
        else  if (cusID != null) 
        {
            List customer = customerEntityFacade.findAll();
            for(Iterator it = customer.iterator(); it.hasNext();)
            {
                CustomerEntity elem = (CustomerEntity) it.next();
                if(elem.getCustomerid().toString().equals(cusID))
                {
                    cus_ID = elem.getCustomerid()+"";
                    cus_Name = elem.getName();
                    cus_Address = elem.getAddress();
                    cus_tno = elem.getContactno();
                }
            }
            
        }
        
        
        PrintWriter out = response.getWriter();
        try {
            /*
             * TODO output your page here. You may use following sample code.
             */
            
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet AddCustomer</title>");            
            out.println("</head>");
            out.println("<div align='center'>");
            out.println("<body bgcolor='#CCCCCC'>");
            out.println("<a href = 'Mainindex'>Main Window | </a>");
            out.println("<a href = 'AddCustomer'>Add new customer | </a>");
            out.println("<a href = 'ListCustomers'>View Customers | </a>");
            out.println("<a href = 'AddCustomerOrder'>Add new customer Order | </a>");
            out.println("<a href = 'ListCustomerOrders'>View Customers Orders</a>");
            out.println("<h1>Add/Update Customer Details</h1>");
            
            
            
            out.println("<form>");
            out.println("<table width='600' height='300' border='1'>");
            out.println("<tr>");
            out.println("<td>Customer Id :</td><td><input type ='text' name ='customerID' value='"+cus_ID+"'></td>");
            out.println("</tr>");
            out.println("<tr>");
            out.println("<td>Customer Name : </td><td><input type ='text' name ='name' value='"+cus_Name+"'></td>");
            out.println("</tr>");
            out.println("<tr>");
            out.println("<td>Customer Address : </td><td><textarea name = 'address'>"+cus_Address+"</textarea></td>");
            out.println("</tr>");
            out.println("<tr>");
            out.println("<td>Contact No : </td><td><input type ='text' name ='contactNo' value='"+cus_tno+"'></td>");
            out.println("</tr>");
            out.println("</table>");
            out.println("<br/>");
            out.println("<input type='hidden' name='cusKey' value='"+cusID+"'/>");
            out.println("<input type='submit' name='act' Value='Add Customer'>");
            out.println("<input type='submit' name='act' Value='Update Customer' >");
            out.println("<h3>"+out_msg+"</h3>");
            out.println("</form>");
            
            out.println("</body>");
            out.println("</div>");
            out.println("</html>");
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
